package com.itqf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itqf.entity.TbItem;
import com.itqf.service.CacheService;
import com.itqf.service.TbItemService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/3/16
 * @Time: 下午4:26
 */
@Controller
public class MyController {

    //注入service

    //用dubbo的方式调用提供者提供的服务
    @Reference(version = "2.0")//com.alibaba.dubbo.config.annotation.Reference
    private TbItemService tbItemService;

    @Reference(version = "4.0")
    private CacheService cacheService;



    @RequestMapping("/findAll")
    @ResponseBody
    public List<TbItem>  find(){

         String json = cacheService.get("tb_item_list");
         List<TbItem> list = null;
         if (json!=null&&!json.equals("")){
             System.out.println("走缓存！！！");

             //list = objectMapper.convertValue(json,List.class);
                list = JSON.parseArray(json,TbItem.class);
             return  list;
         }else{
             System.out.println("走db！！！");
             list = tbItemService.findAll();
             cacheService.set("tb_item_list",JSON.toJSONString(list));
         }

        return list ;
    }

    @RequestMapping("/saveItem")
    @ResponseBody
    public JSONObject   save(TbItem tbItem) throws InterruptedException {
        JSONObject jsonObject = new JSONObject();
        //延迟双删
        cacheService.del("tb_item_list");
       // TimeUnit.MICROSECONDS.sleep(200);
        int i = tbItemService.saveTbItem(tbItem);
        if (i>0){
            jsonObject.put("code",1);
            jsonObject.put("msg","新增成功！");
        }else{
            jsonObject.put("code",0);
            jsonObject.put("msg","新增失败！");
        }
        TimeUnit.MICROSECONDS.sleep(200);
        cacheService.del("tb_item_list");

        return  jsonObject;
    }



}
